import React from 'react';
import {
    Button,
    Text,
    View,
    Image,
    StyleSheet,
    Dimensions,
    StatusBar,
    ActivityIndicator,
    FlatList,
    ScrollView,
    RefreshControl,
    Animated,
    TouchableHighlight,
    TextInput,
    TouchableOpacity, DeviceEventEmitter, Modal, Switch
} from 'react-native';
import Swiper from 'react-native-swiper';
import { MarqueeHorizontal, MarqueeVertical } from 'react-native-marquee-ab';
import Styles from './Styles';
const { width, height } = Dimensions.get('window')

import app from '../../../app.json';
import Ugame from '../../../Ugame';
import Httpc from "../../utils/Httpc";
import Utils from "../../utils/Utils";
import Football from "../../utils/Football";
import REQUEST from "../../../REQUEST";
import ScrollableTabView, { ScrollableTabBar } from "react-native-scrollable-tab-view";
import Recommend from "../News/Recommend";
var weekday = new Array(7);
weekday[0] = "星期天";
weekday[1] = "星期一";
weekday[2] = "星期二";
weekday[3] = "星期三";
weekday[4] = "星期四";
weekday[5] = "星期五";
weekday[6] = "星期六";

export default class Follow extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            toastModelVisible: false,
            message: '',
            postBetData: {},
            beishuInput: "1",
            isOn: true,
            commis: 0.01,
            IsShow: 0,//0截止后可见1完全公开
            Metro: '',
        };
        this.game_model = '';
        this.Title = "";
        this.name = [];
        this.betNumber = {};
        this.danlists = [];
        this.isPhoto = 0;
    }
    static navigationOptions = {
        title: '发布跟单',
        //header: null,  //隐藏顶部导航栏
        //tabBarVisible: false, // 隐藏底部导航栏
        headerStyle: {
            backgroundColor: '#d0162e',
            paddingTop: 18,
        },
        headerTintColor: '#fff',
        headerTitleStyle: {
            //fontWeight: 'bold',
        },
    }
    componentDidMount() {
        const { navigation } = this.props;
        this.game_model = navigation.getParam("game_model");
        let postBetData = navigation.getParam("postBetData");
        let beishuInput = navigation.getParam("beishuInput");
        this.Title = postBetData.Title;
        this.name = navigation.getParam("name");
        this.betNumber = navigation.getParam("betNumber");
        this.danlists = navigation.getParam("danlists");
        this.isPhoto = postBetData.isPhoto;

        switch (this.game_model) {
            case 'FootballGame':
                var betAmount = postBetData.betRecords.length * Football.PRICE;
                break;
            case "DLTGame":
                var betAmount = postBetData.betAmount;
                break;
        }
       
        this.setState({
            postBetData: postBetData,
            betAmount: betAmount,
            beishuInput: beishuInput + ''
        })

    }

    do_toast = (str, time) => {
        this.setState({
            message: str,
            toastModelVisible: true
        });
        setTimeout(() => {
            this.setState({
                message: '',
                toastModelVisible: false
            });
        }, time);
    }
    toast = () => {
        return (
            <Modal
                animationType="fade"
                transparent={true}
                visible={this.state.toastModelVisible}
                onRequestClose={() => {
                    this.setState({
                        toastModelVisible: false
                    });
                }}
            >
                <View style={{ flexDirection: 'row', justifyContent: 'center', position: 'absolute', bottom: 100, width: width }}>
                    <Text style={{ backgroundColor: 'rgba(0,0,0,0.5)', color: '#ffffff', borderRadius: 10, height: 40, lineHeight: 40, paddingLeft: 20, paddingRight: 20 }}>{this.state.message}</Text>
                </View>
            </Modal>
        );
    }

    switchValue = (e) => {
        this.setState({
            isOn: e,
        });
    }

    _on_change_commis = (commis) => {
        this.setState({
            commis: commis
        });
    }
    renderCommis() {
        let Commis = app.Commis;
        var itemArr = [];
        for (var i = 0; i < Commis.length; i++) {
            let data = Commis[i];
            let css = Styles.commis_td;
            if (this.state.commis == data) {
                css = Styles.commis_td_on;
            }
            itemArr.push(
                <TouchableOpacity key={data} onPress={() => this._on_change_commis(data)}>
                    <Text style={css}>{parseInt(data * 100)}%</Text>
                </TouchableOpacity>
            );
        }
        return (
            <View>
                <View style={{ flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'flex-start', alignItems: 'center' }}>
                    {itemArr}
                </View>
                <Text style={{ fontSize: 12, color: '#d0162e', marginTop: 5 }}>*中奖税后金额必须大于本金，才可获得以上设定比例的佣金</Text>
            </View>


        );
    }
    _on_reduce_beishuInput = () => {
        if (this.state.beishuInput == '' || Number(this.state.beishuInput) <= 1) {
            return;
        }
        let beishuInput = Number(this.state.beishuInput);
        beishuInput--;
        this.setState({
            beishuInput: beishuInput.toString(),
        });
    }
    _on_increase_beishuInput = () => {
        let beishuInput = this.state.beishuInput;
        if (beishuInput == '' || Number(beishuInput) < 1 || isNaN(Number(beishuInput))) {
            beishuInput = 1;
        }
        beishuInput++;
        this.setState({
            beishuInput: "" + beishuInput
        })
    }
    _onbeishuInputChangeText = (beishuInput) => {
        this.setState({
            beishuInput: Utils.checkbeishuInput(beishuInput)
        })
    }
    _compute_bet_count = () => {
        return Football.betNumberComb(this.name, this.betNumber, this.state.beishuInput, this.danlists);
    }
    _on_change_isshow = (e) => {
        this.setState({
            IsShow: e
        });
    }
    onChangeMetro = (str) => {
        this.setState({
            Metro: str
        });
    }
    _getPostBetData = () => {
        let nameArray = [];
        let name = this.name;
        for (let i = 0; i < name.length; i++) {
            nameArray.push(name[i].split("/")[0]);
        }
        let betNumber = [];
        for (let key in this.betNumber) {
            let item = this.betNumber[key];
            item.NoID = item.NoID.replace(/_/g, '');
            betNumber.push(item);
        }
        var postBetData = {
            name: nameArray.join(","),
            isPhoto: this.isPhoto,
            betNumber: betNumber,
            betRecords: this._compute_bet_count()
        }
        return postBetData;
    }
    do_bet_order = () => {
        let { IsFollow, commis, IsShow, Metro, isOn } = this.state;
        if (this.name.length == 0) {
            this.do_toast('请选择玩法', 500);
            return;
        }
        switch (this.game_model) {
            case 'FootballGame':
                var postBetData = this._getPostBetData();
                //单笔金额不能超过20万元
                if (postBetData.betRecords.length * Number(this.state.beishuInput) > app.maxBetAmount) {
                    this.do_toast('单笔金额不能超过20万元', 500);
                    return;
                }
                //end
        
                postBetData.IsFollow = 1;
                postBetData.Title = this.Title;
                postBetData.Commis = isOn ? commis : 0;
                postBetData.IsShow = IsShow ? 1 : 0;
                postBetData.Metro = Metro;
                this.props.navigation.navigate('BetOrder', {
                    type: 1,
                    postBetData: postBetData,
                    beishuInput: this.state.beishuInput,
                    game_model: "FootballGame",
                })
                break;
            case "DLTGame":
                var postBetData = this.state.postBetData;
                var Mult = Number(this.state.beishuInput);    
                postBetData.IsFollow = 1;
                postBetData.Commis = isOn ? commis : 0;
                postBetData.IsShow = IsShow ? 1 : 0;
                postBetData.Metro = Metro;
                postBetData.Mult = Mult;                
                for(let i=0;i<postBetData.betRecords.length;i++){
                    postBetData.betRecords[i].multNum = Mult;
                }
                postBetData.betAmount=(postBetData.betRecords.length * app.PRICE * Mult * (postBetData.IncNum == '' ? 1 : postBetData.IncNum)) * (postBetData.IsAdd == 0 ? 1 : 1.5)
                //单笔金额不能超过2万元
                if (postBetData.betAmount > app.DLTMaxBetAmount) {
                    this.do_toast('单笔金额不能超过2万元', 500);
                    return;
                }
                //end
                this.props.navigation.navigate('BetOrder', {
                    type: 1,
                    postBetData: postBetData,
                    game_model: "DLTGame",
                })
                break;
        }
    }
    render() {
        let { isOn, IsShow, Metro, betAmount } = this.state;
        return (
            <View style={Styles.container}>
                <StatusBar translucent={true} backgroundColor="transparent" />
                <ScrollView >
                    <View style={{ backgroundColor: '#ffffff', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', paddingLeft: 16, paddingRight: 16, height: 45 }}>
                        <View style={{ flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'center' }}>
                            <Text style={{ color: '#333333' }} >单倍金额：</Text>
                            <Text style={{ color: '#d0162e' }}>{betAmount}元</Text>
                        </View>
                        <View style={Styles.beishu}>
                            <Text style={{ color: '#333333' }}>自购</Text>
                            <View style={Styles.beishu_input}>
                                <TouchableOpacity onPress={() => this._on_reduce_beishuInput()}>
                                    <View style={{ paddingLeft: 10, paddingRight: 10, height: 30, flexDirection: 'row', justifyContent: 'center', alignItems: 'center' }}>
                                        <Image resizeMode="cover" source={require('../../image/js_img_icon_subtract.png')} />
                                    </View>
                                </TouchableOpacity>
                                <TextInput
                                    style={{ height: 30, padding: 0, lineHeight: 30, textAlign: 'center', width: 50, borderLeftWidth: 0.5, borderRightWidth: 0.5, borderColor: '#939393' }}
                                    value={this.state.beishuInput.toString()}
                                    keyboardType='numeric'
                                    placeholder={"1"}
                                    onChangeText={(beishuInput) => this._onbeishuInputChangeText(beishuInput)}
                                />
                                <TouchableOpacity onPress={() => this._on_increase_beishuInput()}>
                                    <View style={{ paddingLeft: 10, paddingRight: 10, height: 30, flexDirection: 'row', justifyContent: 'center', alignItems: 'center' }}>
                                        <Image resizeMode="cover" source={require('../../image/js_img_sub_icon_add.png')} />
                                    </View>
                                </TouchableOpacity>
                            </View>
                            <Text style={{ color: '#333333' }}>倍</Text>
                        </View >
                    </View>
                    <View style={{ backgroundColor: '#ffffff', marginTop: 15, paddingLeft: 16, paddingRight: 16 }}>
                        <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
                            <Text style={{ color: '#333333' }}>中奖佣金</Text>
                            <Switch
                                // disabled={true}//是否可以响应,默认为false,true是无法点击
                                onTintColor='#f68b2c'  //开关打开时的背景颜色
                                thumbTintColor='#ffffff' //开关上原形按钮的颜色
                                tintColor='#cccccc' //关闭时背景颜色
                                style={{ height: 50 }}
                                //当状态值发生变化值回调
                                // onValueChange={() => this.setState({isOn: !this.state.isOn})} 

                                value={isOn}//默认状态
                                onValueChange={(e) => this.switchValue(e)}
                            />
                        </View>
                        {isOn ? this.renderCommis() : null}
                        <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', paddingTop: 10, paddingBottom: 10 }}>
                            <Text style={{ color: '#333333' }}>保密设置</Text>
                            <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
                                <TouchableOpacity onPress={() => this._on_change_isshow(1)}>
                                    <Text style={IsShow == 1 ? Styles.tab_on : Styles.tab}>完全公开</Text>
                                </TouchableOpacity>
                                <TouchableOpacity onPress={() => this._on_change_isshow(0)}>
                                    <Text style={IsShow == 0 ? Styles.tab_on : Styles.tab}>截止后可见</Text>
                                </TouchableOpacity>
                            </View>
                        </View>
                    </View>
                    <View style={{ flexDirection: 'column', justifyContent: 'center', alignItems: 'center', paddingTop: 10, paddingBottom: 10, marginTop: 10, backgroundColor: '#ffffff' }}>
                        <Text style={{ color: '#333333', width: width - 32, paddingBottom: 10 }}>方案描述</Text>
                        <View style={{ width: width - 32 }}>
                            <TextInput
                                multiline={true}
                                style={{ textAlignVertical: 'top', height: 100, borderColor: '#e6e6e6', borderWidth: 1, width: width - 32, borderRadius: 3 }}
                                onChangeText={text => this.onChangeMetro(text)}
                                value={Metro}
                                placeholder={"方案描述(140字以内)"}
                                maxLength={140}
                            />
                        </View>
                    </View>
                    <View style={{ flexDirection: 'column', justifyContent: 'center', alignItems: 'center', paddingTop: 10, paddingBottom: 10, marginTop: 10 }}>
                        <Text style={{ color: '#333333', width: width - 32, paddingBottom: 10 }}>注意事项</Text>
                        <View style={{ width: width - 32 }}>
                            <Text style={{ color: '#666666', paddingBottom: 5 }}>1.预计佣金根据每个跟单者预计奖金估算，店主实际出票时，赔率会有变化，可能存在误差</Text>
                            <Text style={{ color: '#666666', paddingBottom: 5 }}>2.佣金金额从跟单者中奖金额中扣除，逐笔发放</Text>
                            <Text style={{ color: '#666666', paddingBottom: 5 }}>3.个别跟单者通过线下方式购彩，可能无法获取佣金</Text>
                        </View>
                    </View>
                </ScrollView>
                <TouchableOpacity style={Styles.betOrder} onPress={() => this.do_bet_order()}>
                    <Text style={Styles.betOrder}>付款并发布</Text>
                </TouchableOpacity>
                {this.toast()}
            </View>
        )
    }



}
